package com.siyoumi.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.siyoumi.component.XBean;
import com.siyoumi.component.XRedis;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.entity.*;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.mapper.SysAppMapper;
import com.siyoumi.util.XJson;
import com.siyoumi.util.XReturn;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class SysAppService
        extends ServiceImplBase<SysAppMapper, SysApp> {
    static public SysAppService getBean() {
        return XSpringContext.getBean(SysAppService.class);
    }

    /**
     * 根据帐号，获取站点所有应用
     *
     * @param entityAcc 帐号
     * @param getCache  从缓存中获取
     * @return 应用列表
     */
    public List<SysApp> getApps(SysAccount entityAcc, Boolean getCache) {
        SysAppService ins = SysAppService.getBean();
        String redisKey = ins.getEntityCacheKey("apps");

        String json = XRedis.getBean().getAndSetData(redisKey, key ->
        {
            QueryWrapper<SysApp> query = getAppsQuery(entityAcc);
            return getBaseMapper().selectList(query);
        }, getCache);

        return XJson.parseArray(json, SysApp.class);
    }

    /**
     * 应用ID
     *
     * @return 应用ID
     */
    public List<String> getAppIds(SysAccount entityAcc, Boolean getCache) {
        List<SysApp> apps = getApps(entityAcc, getCache);
        return apps.stream().map(SysApp::getApp_id).collect(Collectors.toList());
    }


    public QueryWrapper<SysApp> getAppsQuery(SysAccount entityAcc) {
        //类型
        List<String> types = new ArrayList<>();
        types.add("common"); //通用应用类型
        types.add(entityAcc.getAcc_x_id());
        if (SysAccountService.getBean().isSuperAdmin(entityAcc)) {
            //超管
            types.add("super_admin");
        }
        if (SysAccountService.getBean().isDev(entityAcc)) {
            //开发者
            types.add("super_admin");
            types.add("dev");
        }

        QueryWrapper<SysApp> query = q();
        query.eq("app_enable", 1)
                .and(q ->
                {
                    //关系应用
                    q.in("app_type", types)
                            .or().exists("SELECT 1 FROM wx_app.t_s_accsuper_zzz_app " +
                                    "WHERE acczapp_x_id = {0} AND acczapp_app_id = app_id", XHttpContext.getX());
                });
        SysAccsuperConfig entityConfig = XHttpContext.getXConfig();
        if (entityConfig.wxApp()) {
            query.eq("app_is_wxapp", 1);
        } else {
            query.eq("app_is_wx", 1);
        }
        return query;
    }


    /**
     * 获取账号下所有关联应用
     *
     * @return 应用ID
     */
    public List<String> getZzzAppIds() {
        SysAccsuperZzzAppService app = SysAccsuperZzzAppService.getBean();

        LambdaQueryWrapper<SysAccsuperZzzApp> query = app.ql();
        query.eq(SysAccsuperZzzApp::getAcczapp_x_id, XHttpContext.getX())
                .select(SysAccsuperZzzApp::getAcczapp_app_id);
        List<SysAccsuperZzzApp> list_apps = app.mapper().selectList(query);

        return list_apps.stream().map(SysAccsuperZzzApp::getAcczapp_app_id).collect(Collectors.toList());
    }


    /**
     * 同步应用
     */
    @Transactional(propagation = Propagation.MANDATORY)
    public XReturn syncApp(List<SysAppRouter> listSrc) {
        if (listSrc.size() <= 0) {
            return EnumSys.ARR_SIZE_0.getR();
        }

        List<SysAppRouter> listSys = SysAppRouterService.getBean().list();
        Integer addCount = 0;
        Integer updateCount = 0;
        for (SysAppRouter entityApprSrc : listSrc) {
            SysAppRouter entity = listSys.stream()
                    .filter(item -> entityApprSrc.getAppr_id().equals(item.getAppr_id()))
                    .findFirst().orElse(null);
            Boolean isAdd = false;
            if (entity == null) {
                isAdd = true;
            }

            SysAppRouter entitySaveOrUpdate = new SysAppRouter();
            XBean.copyProperties(entityApprSrc, entitySaveOrUpdate);
            if (isAdd) {
            } else {
                //不同步appr_meta_title_client
                entitySaveOrUpdate.setAppr_meta_title_client(null);
            }
            SysAppRouterService.getBean().saveOrUpdatePassEqualField(entity, entitySaveOrUpdate);
            //操作成功，更新数量
            Boolean doSet = XHttpContext.get("doSet", false);
            if (doSet) {
                if (isAdd) {
                    addCount++;
                } else {
                    updateCount++;
                }
            }
        }

        XReturn r = XReturn.getR(0);
        r.setData("new_count", addCount);
        r.setData("update_count", updateCount);
        return r;
    }
}
